package com.example.recite_words.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.recite_words.Bean.Questions;
import com.example.recite_words.MainActivity;
import com.example.recite_words.R;
import com.example.recite_words.util.MyDatabaseHelper;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Random;

import de.hdodenhof.circleimageview.CircleImageView;


public class Battle extends MainActivity {
    //private static Context mContext;
    private ImageView b1t,b1f,b2t,b2f,b3t,b3f,b4t,b4f;
    private Button but1,but2,but3,but4;
    private static int seed= 0;
    private String word,def1,def2,def3,def4;
    private CircleImageView my,your;
    private static TextView mScore,uScore,curWord;
    public static int round = 0,rightIndex = 0,urScore=0,myScore=0,en_finish = 0;
    private static  Object wait_me = new Object();
    private static Object wait_you = new Object();
    ArrayList<Questions> data= new ArrayList<>();
    ArrayList<Questions> wrongList =new ArrayList<>();
    SharedPreferences sharedpreferences;
    public static final String MyPREFERENCES = "wrongData";
    public static final String value = "wrongNum";
    int wrongNum;

    //websocket
    public static Handler handler=new Handler(Looper.getMainLooper()){//记得destroy
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    urScore+=10;
                    uScore.setText(urScore+"");
                    break;
                case 2:
                    en_finish = 1;
                    new Thread(() -> {
                        synchronized (wait_you) {
                            wait_you.notify();
                            if (round < 10) {
                                try {
                                    wait_you.wait(50);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            return;
                        }
                    }).start();
                    break;
                case 3:{//匹配
                    synchronized (Waiting.wait_en) {
                        String temp = (String) msg.obj;
                        int pos1,pos2;
                        pos1 = 0;
                        pos2 = temp.indexOf("|");
                        MainActivity.en_user.setId(temp.substring(pos1,pos2));
                        temp = temp.substring(pos2 + 1,temp.length());
                        pos2 = temp.indexOf("|");
                        MainActivity.en_user.setNickName(temp.substring(0,pos2));
                        temp = temp.substring(pos2 + 1);
                        seed = Integer.valueOf(temp).intValue();
                        //String en_email = (String) msg.obj;
                        //MainActivity.en_user.setId(en_email);
                        Waiting.wait_en.notify();
                    }
                    return;
                }
            }
        }};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_battle);
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        wrongNum = sharedpreferences.getInt(value, 0);
        //sharedpreferences.edit().clear().commit();
        my = findViewById(R.id.ba_my);
        Uri uri = MainActivity.TheUser.IconToUri();
        if(uri != null){
            my.setImageURI(uri);
        }
        else {
            my.setImageResource(R.drawable.user_icon);
        }
        your = findViewById(R.id.ba_your);
        uri = MainActivity.en_user.IconToUri();
        if(uri != null){
            your.setImageURI(uri);
        }
        else {
            your.setImageResource(R.drawable.user_icon);
        }
        //initial data
        MyDatabaseHelper db1=new MyDatabaseHelper(this);
        try {
            db1.createDB();
        } catch (IOException ioe) {
            throw new Error("Database not created....");
        }

        try {
            db1.openDB();
        } catch (SQLException sqle) {
            throw sqle;
        }

        SQLiteDatabase db;
        db= openOrCreateDatabase("words", Context.MODE_PRIVATE, null);

        Random rand = new Random(seed);
        int index[]=new int[10];//十个随机数种子且互不相同
        for(int i=0;i<10;++i)
            index[i] = Math.abs(rand.nextInt() %3900);
            //index[i]=getNum(2000);

        Cursor cursor=db.query("Sheet1",null,null,
                null,null,null,null);
        for(int i=0;i<10;++i){
            cursor.moveToPosition(index[i]);
            Questions question=new Questions();
            data.add(question);
            int temp=cursor.getColumnIndex("words");
            if(temp>=0)  data.get(i).word=cursor.getString(temp);
            temp=cursor.getColumnIndex("translation");
            if(temp>=0) {
                String[] meaning = cursor.getString(temp).split("\n");
                data.get(i).true_meaning=meaning[0];
            }
            for(int j=0;j<3;++j) {
                cursor.moveToNext();
                temp = cursor.getColumnIndex("translation");
                if (temp >= 0) {
                    String[] meaning = cursor.getString(temp).split("\n");
                    data.get(i).false_meaning[j] =meaning[0];
                }
            }
        }
        cursor.close();
        //initial end


        but1 = (Button)findViewById(R.id.but1);
        but2 = (Button)findViewById(R.id.but2);
        but3 = (Button)findViewById(R.id.but3);
        but4 = (Button)findViewById(R.id.but4);
        mScore = (TextView)findViewById(R.id.mScore);
        uScore = (TextView)findViewById(R.id.uScore);
        curWord= (TextView)findViewById(R.id.word);
        mScore.setText(myScore+"");
        uScore.setText(urScore+"");
        b1t=(ImageView)findViewById(R.id.but1cor);
        b1f=(ImageView)findViewById(R.id.but1wro);
        b2t=(ImageView)findViewById(R.id.but2cor);
        b2f=(ImageView)findViewById(R.id.but2wro);
        b3t=(ImageView)findViewById(R.id.but3cor);
        b3f=(ImageView)findViewById(R.id.but3wro);
        b4t=(ImageView)findViewById(R.id.but4cor);
        b4f=(ImageView)findViewById(R.id.but4wro);
        initWord(round);
        but1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(round >= 10)
                    return;
                if(rightIndex == 0) {  //按对了
                    myScore+=10;
                    Waiting.client.send("add");
                    b1t.setVisibility(View.VISIBLE);
                }
                else{
                    wrongList.add(data.get(round));
                    ++wrongNum;
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putInt(value, wrongNum);
                    editor.putInt("wrong"+wrongNum,index[round]);
                    editor.apply();
                    b1f.setVisibility(View.VISIBLE);
                }

                ++round;
                initWord(round);
            }
        });
        but2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(round >= 10)
                    return;
                if(rightIndex == 1) {  //按对了
                    myScore+=10;
                    Waiting.client.send("add");
                    b2t.setVisibility(View.VISIBLE);
                }
                else{
                    wrongList.add(data.get(round));
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putInt(value, wrongNum);
                    editor.putInt("wrong"+wrongNum,index[round]);
                    editor.apply();
                    b2f.setVisibility(View.VISIBLE);

                }

                ++round;
                initWord(round);
            }
        });

        but3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(round >= 10)
                    return;
                if(rightIndex == 2) {  //按对了
                    myScore+=10;
                    Waiting.client.send("add");
                    b3t.setVisibility(View.VISIBLE);
                }
                else {
                    wrongList.add(data.get(round));
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putInt(value, wrongNum);
                    editor.putInt("wrong"+wrongNum,index[round]);
                    editor.apply();
                    b3f.setVisibility(View.VISIBLE);
                }
                ++round;
                initWord(round);
            }
        });
        but4.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(round >= 10)
                    return;
                if(rightIndex == 3) {  //按对了
                    myScore+=10;
                    Waiting.client.send("add");
                    b4t.setVisibility(View.VISIBLE);
                }
                else{
                    wrongList.add(data.get(round));
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putInt(value, wrongNum);
                    editor.putInt("wrong"+wrongNum,index[round]);
                    editor.apply();
                    b4f.setVisibility(View.VISIBLE);
                }
                ++round;
                initWord(round);
            }
        });


    }
    private void initWord(int round){

        if (round >= 10) {
                new Thread(() -> {
                    synchronized (wait_you) {
                        Waiting.client.send("done");
                        wait_you.notify();
                        if (en_finish == 0) {
                            try {
                                wait_you.wait(50000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        if (myScore >= urScore) {
                            Intent intent = new Intent(Battle.this, Win.class);
                            intent.putExtra("myScore", myScore);
                            intent.putExtra("urScore", urScore);
                            intent.putExtra("wrongList", (Serializable) wrongList);
                            startActivity(intent);
                            return;//必须要有，否则会继续执行。
                        } else if (myScore < urScore) {
                            //Intent intent = new Intent(mContext,Lose.class);
                            Intent intent = new Intent(Battle.this, Lose.class);
                            intent.putExtra("myScore", myScore);
                            intent.putExtra("urScore", urScore);
                            intent.putExtra("wrongList", (Serializable) wrongList);
                            //mContext.startActivity(intent);
                            startActivity(intent);
                            return;
                        }
                    }
                }).start();
            }
                if (round < 10) {
                    b1t.setVisibility(View.INVISIBLE);
                    b1f.setVisibility(View.INVISIBLE);
                    b2t.setVisibility(View.INVISIBLE);

                    b2f.setVisibility(View.INVISIBLE);
                    b3t.setVisibility(View.INVISIBLE);
                    b3f.setVisibility(View.INVISIBLE);
                    b4t.setVisibility(View.INVISIBLE);
                    b4f.setVisibility(View.INVISIBLE);
                    word = data.get(round).word;
                    rightIndex = getNum(4);

                    switch (rightIndex) {
                        case 0:
                            def1 = data.get(round).true_meaning;
                            def2 = data.get(round).false_meaning[0];
                            def3 = data.get(round).false_meaning[1];
                            def4 = data.get(round).false_meaning[2];
                            break;
                        case 1:
                            def1 = data.get(round).false_meaning[0];
                            def2 = data.get(round).true_meaning;
                            def3 = data.get(round).false_meaning[1];
                            def4 = data.get(round).false_meaning[2];
                            break;
                        case 2:
                            def1 = data.get(round).false_meaning[0];
                            def2 = data.get(round).false_meaning[1];
                            def3 = data.get(round).true_meaning;
                            def4 = data.get(round).false_meaning[2];
                            break;
                        default:
                            def1 = data.get(round).false_meaning[0];
                            def2 = data.get(round).false_meaning[1];
                            def3 = data.get(round).false_meaning[2];
                            def4 = data.get(round).true_meaning;
                            break;
                    }
                    but1.setText(def1);
                    but2.setText(def2);
                    but3.setText(def3);
                    but4.setText(def4);
                    curWord.setText(word);
                    mScore.setText(myScore + "");
                    uScore.setText(urScore + "");
                }
    }
    private static int getNum(int endNum){
        if(endNum > 0){
            Random random = new Random();
            return random.nextInt(endNum);
        }
        return 0;
    }
}